package com.atguigu.flink.keyStateAndOpeState;

import com.atguigu.flink.bean.WaterSensor;
import com.atguigu.flink.function.WaterSensorMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * 需求：检测每种传感器的水位值，如果连续的两个水位差值超过10，就输出报警
 */
public class OperatorTTL {
    public static void main(String[] args) throws Exception {
        // TODO 1.环境准备
        // 1.1指定流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // 1.2设置并行度
        env.setParallelism(1);
        // TODO 2.从指定的网络端口读取数据
        DataStreamSource<String> socketDS = env.socketTextStream("hadoop102", 8888);
        // TODO 3.对流中数据进行类型转换
        SingleOutputStreamOperator<WaterSensor> wsDS = socketDS.map(new WaterSensorMapFunction());
        // TODO 4.按照传感器的id进行分组
        KeyedStream<WaterSensor, String> keyByDS = wsDS.keyBy(WaterSensor::getId);
        // TODO 5.对分组后的数据进行处理  判断连续的两个水位差值是否超过10  如果超过10，输出报警
        SingleOutputStreamOperator<String> processDS = keyByDS.process(

                new KeyedProcessFunction<String, WaterSensor, String>() {

                    //声明键控状态-值状态（存放的数据是单个值）   虽然声明在成员变量的位置，但是键控状态的作用范围是keyby后的每一个组 ，组和组之间的状态是隔离的
                    //注意：不能在声明状态的时候直接对状态进行初始化，因为这个时候获取不到运行时上下文
                    private ValueState<Integer> lastVcState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        ValueStateDescriptor<Integer> valueStateDescriptor = new ValueStateDescriptor<>("", Integer.class);
                        valueStateDescriptor.enableTimeToLive(StateTtlConfig.newBuilder(Time.seconds(10)).build());
                        lastVcState = getRuntimeContext().getState(valueStateDescriptor);

                    }

                    @Override
                    public void processElement(WaterSensor ws, KeyedProcessFunction<String, WaterSensor, String>.Context ctx, Collector<String> out) throws Exception {
                        //获取当前水位值
                        Integer curVc = ws.getVc();
                        //从状态中获取上次水位值
                        Integer lastVc = lastVcState.value() == null ? 0 : lastVcState.value();
                        //获取id
                        String id = ws.getId();
                        if (Math.abs(lastVc - curVc) > 10){
                            out.collect("传感器" + id + "当前水位值 " + curVc + "和上次的水位值 " + lastVc+" 的差超过10");
                        }
                        lastVcState.update(curVc);
                    }
                }
        );
        // TODO 7.打印输出
        processDS.print();
        // TODO 8.提交作业
        env.execute();

    }
}
